package com.hxd.mall.module.startup

import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.alibaba.android.arouter.launcher.ARouter
import com.hexin.locallibrary.network.OkHttpManager
import com.hxd.mall.BuildConfig
import com.hxd.mall.BuildConfig.baseUrl
import com.hxd.mall.R
import com.hxd.mall.base.BaseInjectActivity
import com.hxd.mall.base.IBaseView
import com.hxd.mall.constant.HxdConstants.Cache_Key_Is_First_Open
import com.hxd.mall.constant.HxdConstants.Channel_Number
import com.hxd.mall.constant.HxdConstants.TB_auther_isgo
import com.hxd.mall.constant.HxdConstantsAccount.isLogin
import com.hxd.mall.constant.HxdConstantsAccount.token
import com.hxd.mall.constant.HxdConstantsAccount.userInfo
import com.hxd.mall.constant.HxdConstantsRouterPath.Product.path_hxd_main_page
import com.hxd.mall.constant.HxdGlobalInfo
import com.hxd.mall.constant.HxdGlobalInfo.instance
import com.hxd.mall.constant.HxdGlobalInfo.versionCode
import com.hxd.mall.module.account.UserInfo
import com.hxd.mall.network.base.BaseRequest
import com.hxd.mall.network.service.ManagerFunctionApi
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.getBooleanData
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.getStringData
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.saveBooleanData
import com.hxd.mall.utils.local.NavigationUtil.routerNavigation
import com.hxd.mall.utils.local.StackManageUtil.removeActivity
import com.hxd.mall.utils.local.ThirdInitUtil
import com.hxd.mall.utils.local.ThirdInitUtil.hostChange
import com.hxd.mall.utils.open.CountDownTimerUtil.startTimer
import com.hxd.mall.utils.open.DeviceUuidUtil.deviceUuid
import com.hxd.mall.utils.open.GsonUtil
import com.hxd.mall.utils.open.addSetOnClickListener
import com.hxd.mall.widget.refresh.HXRefreshFooter
import com.hxd.mall.widget.refresh.HXRefreshHeader
import com.hxd.threelibrary.getAlibcClient
import com.meituan.android.walle.WalleChannelReader
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import crossoverone.statuslib.StatusUtil
import io.reactivex.Observable
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_page_welcome_third.view.*
import kotlinx.android.synthetic.main.activity_welcome.*
import org.jetbrains.anko.backgroundResource
import org.jetbrains.anko.dip
import org.jetbrains.anko.displayMetrics
import java.util.concurrent.TimeUnit

/**
 * 欢迎页
 */
class WelcomeActivity : BaseInjectActivity<IWelcomePresenter>(), IBaseView {

    override fun attachLayoutRes() = R.layout.activity_welcome

    override fun initViews() {
        //重新进入app 可以重新授权
        TB_auther_isgo = true
        iv_splash_welcome.postDelayed({
            if (BuildConfig.DEBUG) {
                ARouter.openLog()
                ARouter.openDebug()
            }
            ARouter.init(instance)

            //初始化三方库
            ThirdInitUtil.thirdInitUtils(instance)

            //初始化设备信息
            initDeviceInfo()
            //初始化用户信息
            initUserInfo()

            //阿里百川初始化
            getAlibcClient().init(instance)

            //初始化下拉刷新的控件
            configureSmartRefreshLayout()

            //初始化网络请求
            val baseUrl = if (getStringData("domain").isEmpty()) baseUrl else getStringData("domain")
            OkHttpManager.init(baseUrl, HxdGlobalInfo.instance.cacheDir, hashMapOf())

            //获取服务域名
            //configureDomin()
            open()
        }, 300)
    }

    override fun initData() {
    }

    override fun netSuccess(vararg t: Any) {
        /*if (!isFinishing && t.isNotEmpty()) {
            iv_splash_welcome.load(t[0].toString(), 0, 0)
        }*/
    }

    private fun openToMain() {
        val timer = startTimer(3, {
            goto()
        }, {
            tv_tiaoguo_welcome.text = String.format("跳过 $it s")
        })
//        iv_splash_welcome.load(R.mipmap.splash, 0, 0)

        tv_tiaoguo_welcome.run {
            visibility = View.VISIBLE
            addSetOnClickListener(this) {
                goto()
                timer.dispose()
            }
        }
        vp_welcome.visibility = View.GONE
    }

    private fun goto() {
        if (isFinishing) return
        routerNavigation(path_hxd_main_page)
    }

    override fun onStop() {
        super.onStop()
        removeActivity(this)
    }

    private fun makePager(id: Int) = ImageView(this).apply {
        //        backgroundResource = id
        setImageResource(id)
        scaleType = ImageView.ScaleType.CENTER_CROP
    }

    private fun initWelcomeView() {
        tv_tiaoguo_welcome.visibility = View.GONE
        val fourView =
            LayoutInflater.from(this).inflate(R.layout.activity_page_welcome_third, null).apply {
                view_iv_welcome.setImageResource(R.mipmap.guide_four)
                view_iv_welcome.scaleType = ImageView.ScaleType.CENTER_CROP
                addSetOnClickListener(welcome_btn) {
                    HxdGlobalInfo.isFirst = false
                    saveBooleanData(Cache_Key_Is_First_Open, true)
                    goto()
                }
            }
        arrayListOf(
            makePager(R.mipmap.guide_first),
            makePager(R.mipmap.guide_second),
            makePager(R.mipmap.guide_three),
            fourView
        ).run {
            vp_welcome.adapter = WelcomeAdapter(this)
        }
        //数据加载完了在展示view
        iv_splash_welcome.visibility = View.GONE
        vp_welcome.visibility = View.VISIBLE
    }

    private fun configureSmartRefreshLayout() {
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, _ ->
            val layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                dip(80)
            )
            val head = HXRefreshHeader(context)
            head.layoutParams = layoutParams
            head
        }
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, _ ->
            val layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                dip(60)
            )
            val foot = HXRefreshFooter(context)
            foot.layoutParams = layoutParams
            foot
        }
    }

    private fun open() {
        /**
         * 将是否需要重启的标记改变一下值，在应用退出后台再次进入时异常重启application而
         * 导致全局参数初始化，用此标记信息判断是否要重启应用
         */
        HxdGlobalInfo.isReStart = !HxdGlobalInfo.isReStart
        if (!getBooleanData(Cache_Key_Is_First_Open, false))
            initWelcomeView()
        else
            openToMain()
    }

    /**
     * 服务域名切换
     */
//    private fun configureDomin() {
//        BaseRequest.request(
//            ManagerFunctionApi.mIConfigureFunctionApi.systemDomin, this, {
//                hostChange(it.string())
//
//                open()
//            }, {
//                open()
//            })
//    }

    private fun initUserInfo() {
        token = getStringData("token", "")
        isLogin = token?.isNotEmpty() ?: false
//        val variable = getStringData(Cache_Key_User_Info)
//        if (!TextUtils.isEmpty(variable)) {
//            userInfo = GsonUtil.json2bean(variable, UserInfo::class.java)
//        }
    }

    private fun initDeviceInfo() {
        // 初始化状态栏高度
        HxdGlobalInfo.statusBarHeight = StatusUtil.getStatusBarHeight(instance)
        versionCode = packageManager.getPackageInfo(packageName, 0).versionName
        HxdGlobalInfo.deviceUUID = deviceUuid(instance)
        //NetUtil.getNetIp()
        displayMetrics.run {
            HxdGlobalInfo.deviceDensity = this.density
            HxdGlobalInfo.deviceWidth = this.widthPixels
            HxdGlobalInfo.deviceHeight = this.heightPixels
        }
        Channel_Number = WalleChannelReader.getChannel(this) ?: ""
    }

}